package com.sgcc.ln.pmos.e_ln_mall.activity;


import android.content.Intent;
import android.graphics.Canvas;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.sgcc.ln.pmos.arouter.mall.MallArouterPath;
import com.sgcc.ln.pmos.common.base.MvpBaseRecycleActivity;
import com.sgcc.ln.pmos.common.bean.EventCenter;
import com.sgcc.ln.pmos.common.bean.PackageBean;
import com.sgcc.ln.pmos.common.http.HttpInterConst;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.http.MvpNetCallback;
import com.sgcc.ln.pmos.common.utils.ArguConstant;
import com.sgcc.ln.pmos.common.utils.ImmersionBarUtils;
import com.sgcc.ln.pmos.common.utils.PackageContrastUtils;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.common.utils.TextUtil;
import com.sgcc.ln.pmos.e_ln_mall.adapter.ComparisonListAdapter;
import com.sgcc.ln.pmos.e_ln_mall.bean.MallGoodsBean;
import com.sgcc.ln.pmos.e_ln_mall.contract.ComparisonListContract;
import com.sgcc.ln.pmos.e_ln_mall.presenter.ComparisonListPresenter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @author ChaoAJ
 * @describe 套餐对比
 */

@Route(path = MallArouterPath.MALL_COMPARISONLIST)
public class ComparisonListActivity extends MvpBaseRecycleActivity<PackageBean, ComparisonListPresenter> implements ComparisonListContract.View {

    private TextView mTvComparisonListFooterStart;
    private LinearLayout mLLComparisonListFooterStart;
    private ArrayList<PackageBean> selectPackageList = new ArrayList<>();
    private ComparisonListAdapter comparisonListAdapter;

    @Override
    protected void initViews() {
        super.initViews();
        ImmersionBarUtils.initBaseBar(this);
        mTvComparisonListFooterStart = findViewById(R.id.tv_comparisonListFooter_start);
        mLLComparisonListFooterStart = findViewById(R.id.ll_comparisonListFooter_start);
//        adapter.addFooterView(getLayoutInflater().inflate(R.layout.item_footer_comparison_list_layout, null));
        refreshLayout.setEnablePureScrollMode(true);
    }

    @Override
    public String getTitleText() {
        return "套餐对比";
    }

    @Override
    public View getFooterLayout(RelativeLayout parent) {
        return getLayoutInflater().inflate(R.layout.footer_comparison_list_layout, parent, false);
    }

    @Override
    protected void initData() {
        super.initData();
        title_bar.setRightIcon(R.mipmap.go_main, view -> goMainActivity());
        mLLComparisonListFooterStart.setOnClickListener(view -> {
            if (selectPackageList.size() == 0) {
                ToastUtils.showShort("至少选择一个商品");
                return;
            }
            Intent intent = new Intent(this, ComparisonDetailActivity.class);
            intent.putExtra("selectPackageList", selectPackageList);
            ActivityUtils.startActivity(intent);
        });
//        mPresenter.getComparisonData(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        selectPackageList.clear();
        mPresenter.getComparisonData(false);
        setText();
    }

    @Override
    protected ComparisonListPresenter createPresenter() {
        return new ComparisonListPresenter();
    }

    @Override
    public BaseQuickAdapter getAdapter() {
        comparisonListAdapter = new ComparisonListAdapter(mContext);

        comparisonListAdapter.getDraggableModule().setSwipeEnabled(true);//滑动删除
        comparisonListAdapter.getDraggableModule().setOnItemSwipeListener(new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {


            }

            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                PackageBean packageBean = PackageContrastUtils.getPackageContrastList().get(pos);
                for (PackageBean bean : selectPackageList) {
                    if (packageBean.getCombId().equals(bean.getCombId())) {
                        selectPackageList.remove(bean);
                        setText();
                        break;
                    }
                }
                PackageContrastUtils.deletContrast(packageBean.getCombId());
                EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_CONTRAST));

            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {

            }
        });
        comparisonListAdapter.setOnItemClickListener((adapter, view, position) -> {
            PackageBean item = comparisonListAdapter.getItem(position);


            if (selectPackageList.size() == 3 && !item.isSelect()) {
                ToastUtils.showShort("最多只能选择三个");
                return;
            }
            if (item.isSelect()) {
                item.setSelect(false);
                comparisonListAdapter.notifyItemChanged(position);
                if (selectPackageList.contains(item))
                    selectPackageList.remove(item);
                setText();
            } else
                getGoodsList(item, position);
        });
        return comparisonListAdapter;
    }


    public void getGoodsList(PackageBean packageBean, int position) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", 1);
        params.put("pageSize", 5);
        params.put("combName", packageBean.getCombCode());
        params.put("ratioId", SPUtils.getInstance().getString("ratioId", "1"));
        params.put("membersSdId", "");
        params.put("sort", "");
        params.put("soldEnergySort", "");
        params.put("avgPriceSort", "");
        params.put("createDateSort", "");
        params.put("packageInfoCombVo", new HashMap<>());
        params.put("_t", System.currentTimeMillis());
        HttpRequestUtils.getInstance().request(params, HttpInterConst.HOME_PACKAGE,
                new MvcNetCallback<MallGoodsBean>(true) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                    }

                    @Override
                    public void onResponse(MallGoodsBean response, int id) {
                        super.onResponse(response, id);
                        if (response != null) {
                            if (response.getCode() == 200) {
                                if (null != response.getData() && null != response.getData().getData()
                                        && response.getData().getData().size() > 0) {
                                    packageBean.setSelect(true);
                                    comparisonListAdapter.notifyItemChanged(position);
                                    selectPackageList.add(packageBean);
                                } else {
                                    comparisonListAdapter.remove(packageBean);
                                    PackageContrastUtils.deletContrast(packageBean.getCombId());
                                    EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_CONTRAST));
                                    ToastUtils.showLong("商品不存在或已下架");
                                }
                                setText();
                            } else {
                                if (!TextUtils.isEmpty(response.getMsg()))
                                    ToastUtils.showLong(response.getMsg());
                            }
                        } else {
                            comparisonListAdapter.remove(packageBean);
                            PackageContrastUtils.deletContrast(packageBean.getCombId());
                            EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_CONTRAST));
                            ToastUtils.showLong("商品不存在或已下架");
                            setText();
                        }

                    }
                });
    }


    @Override
    public void querySuccess(List<PackageBean> list) {
        loadSuccess(false, list);
    }

    @Override
    public void queryFailed() {

    }

    private void setText() {
        mTvComparisonListFooterStart.setText(selectPackageList.size() == 0 ? "开始比对" :
                String.format("开始比对（%s）", selectPackageList.size()));
    }
}